package com.example.webshiro.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.webshiro.common.SpringContextHolder;
import com.example.webshiro.common.conf.JwtProperties;
import com.example.webshiro.shiro.CurrentUserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.Map;


/**
 * @author LuoYu
 * 2021/4/11
 **/
public class JwtUtil {

    private static Logger log = LoggerFactory.getLogger(JwtUtil.class);

    /**
     * 配置类
     */
    public static JwtProperties properties;



    public static void setProperties(){
        if(properties == null){
            properties = SpringContextHolder.getBean(JwtProperties.class);
        }
    }


    public static boolean verify(String token){
        try {
            String uuid = getStringClaim(token, "uuid");
            String secret = uuid  + Base64EncyUtil.decode(properties.getSignPrivateKey());
            Algorithm hmac256 = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(hmac256).build();
            verifier.verify(token);
            return true;
        }catch (Exception e){
            log.error("JWT校验Token时发生错误 ----> Error:{}", e.getMessage());
            throw e;
        }
    }


    public static String getStringClaim(String token,String claim){
        try {
            final DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim(claim).asString();
        }catch (JWTDecodeException e){
            log.error("JWT解密Token时发生错误 ----> Error:{}", e.getMessage());
            throw  e;
        }
    }


    public static Long getLongClaim(String token,String claim){
        try {
            final DecodedJWT jwt = JWT.decode(token);
            Map<String, Claim> claims = jwt.getClaims();
            return claims.get(claim).asLong();
        }catch (Exception e){
            log.error("JWT解密Token时发生错误 ----> Error:{}", e.getMessage());
            throw  e;
        }
    }


    /**
     * <p>带过期时间的签名</p>
     * @param userInfo  用户信息
     * @return          签名
     */
    public static String signAtExpire(CurrentUserInfo userInfo){
        String secret = userInfo.getUuid().concat(Base64EncyUtil.decode(properties.getSignPrivateKey()));
        Date date = new Date(System.currentTimeMillis() + properties.getTokenExpireTime());
        final Algorithm hmac256 = Algorithm.HMAC256(secret);
        return JWT.create()
                .withClaim("userId", userInfo.getId())
                .withClaim("uuid", userInfo.getUuid())
                .withExpiresAt(date)
                .sign(hmac256);
    }

    /**
     * <p>签名</p>
     * @param userInfo  用户信息
     * @return          签名
     */
    public static String sign(CurrentUserInfo userInfo){
        String secret = userInfo.getUuid().concat(Base64EncyUtil.decode(properties.getSignPrivateKey()));
        final Algorithm hmac256 = Algorithm.HMAC256(secret);
        return JWT.create()
                .withClaim("userId", userInfo.getId())
                .withClaim("uuid", userInfo.getUuid())
                .sign(hmac256);

    }





















}
